package com.epower.web.filter;

import java.util.List;

import javax.servlet.http.Cookie;
import org.apache.struts2.ServletActionContext;

import com.epower.bo.epower.commons.Constants;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * @author bolin.hbc
 * 
 *         用户信息过滤器,当使用某些页面的时候,必须处于登录的状态
 * 
 */
public class LoginInterceptor extends AbstractInterceptor {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private List<String> urls = Constants.LOGIN_URLS;

	@Override
	public String intercept(ActionInvocation invoke) throws Exception {
		String requestUrl = ServletActionContext.getRequest().getRequestURI().toString();

		boolean isLogin = false;
		// 处于登录状态
		if (ServletActionContext.getRequest().getSession().getAttribute(Constants.USER_NAME) != null) {
			isLogin = true;
		}
		if (!isLogin) {
			Cookie allCookie[] = ServletActionContext.getRequest().getCookies();
			// 沒有处于登录状态,不过需要使用cookie到达登录状态
			if (allCookie != null) {
				for (Cookie cookie : allCookie) {
					if (Constants.USER_NAME.equals(cookie.getName())) {
						if (cookie.getValue() != null) {
							ServletActionContext.getRequest().getSession().setAttribute(cookie.getName(), cookie.getValue());
							isLogin = true;
						}
					}
				}
			}
		}
		for (String url : urls) {
			// 表明必须处于登录状态
			if (requestUrl.contains(url)) {
				if (!isLogin) {
					return Action.LOGIN;
				}

			}
		}
		return invoke.invoke();

	}

}
